<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>B站UP主数据分析</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.4.3/echarts.min.js"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        bilibili: {
                            pink: '#FB7299',
                            blue: '#23ADE5',
                            dark: '#18191C',
                        }
                    },
                    fontFamily: {
                        sans: ['"HarmonyOS Sans"', 'sans-serif'],
                    }
                }
            }
        }
    </script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap');

        body {
            font-family: 'Noto Sans SC', sans-serif;
            background-color: #f5f5f5;
        }

        .gradient-bg {
            background: linear-gradient(135deg, #23ADE5 0%, #FB7299 100%);
        }

        .card-hover {
            transition: all 0.3s ease;
        }

        .card-hover:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
        }

        .progress-bar {
            height: 6px;
            border-radius: 3px;
            background-color: #e5e7eb;
            overflow: hidden;
        }

        .progress-fill {
            height: 100%;
            border-radius: 3px;
            background: linear-gradient(90deg, #FB7299, #23ADE5);
        }

        .level-badge {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background-color: #FB7299;
            color: white;
            font-size: 16px;
            font-weight: bold;
            border: 3px solid white;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .chart-container {
            width: 100%;
            height: 400px;
        }

        .loading-spinner {
            border: 4px solid rgba(0, 0, 0, 0.1);
            border-radius: 50%;
            border-top: 4px solid #FB7299;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 20px auto;
        }

        .hover-effect {
            transition: all 0.2s ease;
            cursor: pointer;
        }
        .hover-effect:hover {
            transform: translateY(-2px);
            opacity: 0.9;
        }

        .video-table {
            width: 100%;
            border-collapse: collapse;
        }
        .video-table th {
            background-color: #f3f4f6;
            text-align: left;
            padding: 12px 15px;
            font-weight: 600;
        }
        .video-table td {
            padding: 12px 15px;
            border-bottom: 1px solid #e5e7eb;
        }
        .video-table tr:hover td {
            background-color: #f9fafb;
        }
        .video-title {
            color: #3b82f6;
            cursor: pointer;
        }
        .video-title:hover {
            text-decoration: underline;
            color: #2563eb;
        }

        /* 粉丝勋章样式 */
        .fans-badge {
            display: inline-flex;
            align-items: center;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
            margin-right: 6px;
            background-color: #f0f0f0;
            color: #333;
        }

        /* 不同等级的勋章颜色 */
        .badge-level-5 {
            background-color: #00B5AD; /* 松石绿 */
            color: white;
        }
        .badge-level-15 {
            background-color: #00A1D6; /* 雨后蓝 */
            color: white;
        }
        .badge-level-22 {
            background-color: #1A7BC7; /* 星空蓝 */
            color: white;
        }
        .badge-level-26 {
            background-color: #8A2BE2; /* 紫罗兰 */
            color: white;
        }
        .badge-level-30 {
            background-color: #FB7299; /* 梦镜红 */
            color: white;
        }
        .badge-level-34 {
            background-color: #FF7F00; /* 热力橙 */
            color: white;
        }
        .badge-level-38 {
            background-color: #FFD700; /* 香槟金 */
            color: #333;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body class="bg-gray-100">
<div class="min-h-screen">
    <nav class="bg-white shadow-sm">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16">
                <div class="flex items-center">
                    <div class="flex-shrink-0 flex items-center cursor-pointer hover:opacity-80 transition-opacity duration-200"
                         onclick="window.location.href = 'main'"
                         title="返回主页">
                        <i class="fab fa-bilibili text-3xl text-bilibili-pink hover:scale-105 transition-transform"></i>
                        <span class="ml-2 text-xl font-bold text-gray-800 hover:text-bilibili-pink transition-colors">up数据分析</span>
                    </div>
                </div>
            </div>
        </div>
    </nav>

    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div id="errorContainer" class="mb-4 hidden">
            <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 rounded">
                <div class="flex items-center">
                    <i class="fas fa-exclamation-circle mr-2"></i>
                    <div>
                        <p class="font-bold">错误提示</p>
                        <p id="errorMessage"></p>
                    </div>
                </div>
            </div>
        </div>

        <div class="flex flex-col md:flex-row justify-between items-start">
            <div>
                <h1 id="upName" class="text-2xl font-bold text-gray-800 mb-1">加载中...</h1>
                <div class="flex flex-wrap items-center gap-6">
                    <div id="fansBadgeContainer" class="fans-badge badge-level-5" style="display: none;">
                        <!-- 粉丝勋章将通过JavaScript动态填充 -->
                    </div>
                    <div class="flex items-center text-sm text-gray-500">
                        <i class="fas fa-user-plus mr-1"></i> 粉丝: <span id="upFans">加载中...</span>
                    </div>
                    <div class="flex items-center text-sm text-gray-500">
                        <i class="fas fa-users mr-1"></i> 关注: <span id="upFollowing">加载中...</span>
                    </div>
                    <div class="level-badge">
                        Lv.0
                    </div>
                </div>
            </div>
            <div class="mt-4 md:mt-0 flex space-x-2">
                <button id="updateDataBtn" class="bg-bilibili-blue hover:bg-bilibili-pink text-white font-medium py-2 px-4 rounded-lg transition-all duration-300 flex items-center">
                    <i class="fas fa-sync-alt mr-2"></i>
                    更新数据
                </button>
                <button id="spaceLinkBtn" class="bg-bilibili-pink hover:bg-bilibili-blue text-white font-medium py-2 px-4 rounded-lg transition-all duration-300 flex items-center">
                    <i class="fas fa-external-link-alt mr-2"></i>
                    访问空间
                </button>
            </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
            <div class="bg-white rounded-xl shadow-md overflow-hidden card-hover">
                <div class="p-6">
                    <div class="flex items-center">
                        <div class="p-3 rounded-full bg-blue-100 text-bilibili-blue">
                            <i class="fas fa-play-circle text-xl"></i>
                        </div>
                        <div class="ml-4">
                            <p class="text-sm font-medium text-gray-500">总播放量</p>
                            <p id="totalViews" class="text-2xl font-semibold text-gray-900">加载中...</p>
                        </div>
                    </div>
                    <div class="progress-bar mt-4">
                        <div id="viewsProgress" class="progress-fill" style="width: 0%"></div>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-md overflow-hidden card-hover">
                <div class="p-6">
                    <div class="flex items-center">
                        <div class="p-3 rounded-full bg-pink-100 text-bilibili-pink">
                            <i class="fas fa-comment-dots text-xl"></i>
                        </div>
                        <div class="ml-4">
                            <p class="text-sm font-medium text-gray-500">总弹幕量</p>
                            <p id="totalDanmaku" class="text-2xl font-semibold text-gray-900">加载中...</p>
                        </div>
                    </div>
                    <div class="progress-bar mt-4">
                        <div id="danmakuProgress" class="progress-fill" style="width: 0%"></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 视频列表 -->
        <div class="bg-white rounded-xl shadow-md overflow-hidden card-hover mb-8">
            <div class="p-6">
                <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6">
                    <h2 class="text-lg font-semibold text-gray-800 mb-4 md:mb-0">视频列表</h2>
                    <div class="flex items-center space-x-4">
                        <button id="refreshVideosBtn" class="bg-bilibili-blue hover:bg-bilibili-pink text-white font-medium py-2 px-4 rounded-lg transition-all duration-300 flex items-center">
                            <i class="fas fa-sync-alt mr-2"></i>
                            更新视频数据
                        </button>
                        <div class="relative w-full md:w-64">
                            <input type="text" id="videoSearch" placeholder="搜索视频标题..." class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-bilibili-pink focus:border-transparent">
                            <i class="fas fa-search absolute left-3 top-3 text-gray-400"></i>
                        </div>
                    </div>
                </div>

                <div class="overflow-x-auto">
                    <table class="video-table">
                        <thead>
                        <tr>
                            <th>标题</th>
                            <th>播放量</th>
                            <th>弹幕量</th>
                            <th>时长</th>
                            <th>上传日期</th>
                        </tr>
                        </thead>
                        <tbody id="videoListBody">
                        <!-- 视频列表将通过JavaScript动态填充 -->
                        </tbody>
                    </table>
                </div>

                <div class="flex flex-col sm:flex-row justify-between items-center mt-6">
                    <div class="text-sm text-gray-600 mb-4 sm:mb-0">
                        显示 <span id="startItem">1</span> - <span id="endItem">10</span> 条，共 <span id="totalItems">0</span> 条
                    </div>
                    <div class="flex space-x-2">
                        <button id="prevPage" class="px-4 py-2 border border-gray-300 rounded-lg bg-white text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                            <i class="fas fa-chevron-left mr-1"></i>上一页
                        </button>
                        <div class="flex items-center">
                            <span id="currentPage">1</span>
                            <span class="mx-1">/</span>
                            <span id="totalPages">1</span>
                        </div>
                        <button id="nextPage" class="px-4 py-2 border border-gray-300 rounded-lg bg-white text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                            下一页<i class="fas fa-chevron-right ml-1"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 分析结果 -->
        <div class="bg-white rounded-xl shadow-md overflow-hidden card-hover mb-8">
            <div class="p-6">
                <h2 class="text-lg font-semibold text-gray-800 mb-4">UP主数据分析结果</h2>
                <div id="analysisResult" class="bg-gray-50 p-4 rounded-lg">
                    <div class="loading-spinner"></div>
                </div>
            </div>
        </div>
    </main>
</div>


<script>
    function showError(message) {
        const errorContainer = document.getElementById('errorContainer');
        const errorMessage = document.getElementById('errorMessage');

        errorMessage.textContent = message;
        errorContainer.classList.remove('hidden');
    }

    function hideError() {
        document.getElementById('errorContainer').classList.add('hidden');
    }

    function checkResponse(response) {
        if (!response.ok) {
            throw new Error('网络响应不正常');
        }
        return response.json();
    }

    function checkData(data) {
        if (data.code % 2 !== 0) {
            const errorMsg = data.data || data.msg || '未知错误';
            throw new Error(errorMsg);
        }
        return data.data;
    }

    const url = new URL(window.location.href);
    const params = new URLSearchParams(url.search);
    const uid = params.get('uid');

    if (!uid) {
        showError('未获取到uid号，请确认是否已输入');
        setTimeout(() => {
            window.location.href = 'main';
        }, 3000);
    }

    async function fetchUpBasicInfo(uid) {
        try {
            const response = await fetch(`http://localhost:8080/v1/user/query/${uid}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            const data = await checkResponse(response);
            const userData = checkData(data);

            return {
                name: userData.username,
                gender: userData.gender,
                level: userData.level,
                fans: userData.fansCount,
                following: userData.followCount,
                uid: userData.uid,
                fansBadge: userData.fanMedal
            };
        } catch (error) {
            console.error('获取用户基本信息失败:', error);
            showError(`获取用户基本信息失败: ${error.message}`);
            return null; // 返回 null 而不是抛出错误
        }
    }

    async function fetchVideoData(uid) {
        try {
            const response = await fetch(`http://localhost:8080/v1/video/queryUp/${uid}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            const data = await checkResponse(response);
            const videoData = checkData(data);

            return videoData.map(item => ({
                bvid: item.bv,
                title: item.title,
                views: item.playCount,
                danmaku: item.damuCount,
                duration: item.duration,
                uploadDate: formatDate(item.uploadTime)
            }));
        } catch (error) {
            console.error('获取视频数据失败:', error);
            showError(`获取视频数据失败: ${error.message}`);
            return [];
        }
    }

    document.getElementById('updateDataBtn').addEventListener('click', async function() {
        try {
            this.disabled = true;
            this.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>更新中...';

            const response = await fetch(`http://localhost:8080/v1/user/update/${uid}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            const data = await checkResponse(response);
            const updatedUserData = checkData(data);

            document.getElementById('upName').textContent = updatedUserData.username;
            document.getElementById('upFans').textContent = formatNumber(updatedUserData.fansCount);
            document.getElementById('upFollowing').textContent = formatNumber(updatedUserData.followCount);
            document.querySelector('.level-badge').textContent = `Lv.${updatedUserData.level}`;

            const badgeContainer = document.getElementById('fansBadgeContainer');
            const badgeInfo = parseFansBadge(updatedUserData.fanMedal);

            if (badgeInfo) {
                badgeContainer.style.display = 'inline-flex';
                badgeContainer.innerHTML = `${badgeInfo.name} Lv.${badgeInfo.level}`;
                setFansBadgeStyle(badgeInfo.level);
            }


            await loadAllData();

            alert('用户数据更新成功！');
        } catch (error) {
            console.error('更新用户数据失败:', error);
            showError(`更新用户数据失败: ${error.message}`);
        } finally {
            this.disabled = false;
            this.innerHTML = '<i class="fas fa-sync-alt mr-2"></i>更新数据';
        }
    });

    async function updateVideoData(uid) {
        try {
            const response = await fetch(`http://localhost:8080/v1/video/updateUp/${uid}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            const data = await checkResponse(response);
            const videoData = checkData(data);

            return videoData.map(item => ({
                bvid: item.bv,
                title: item.title,
                views: item.playCount,
                danmaku: item.damuCount,
                duration: item.duration,
                uploadDate: formatDate(item.uploadTime)
            }));
        } catch (error) {
            console.error('更新视频数据失败:', error);
            throw error; // 这里抛出错误，让调用者处理
        }
    }

    function formatDate(dateString) {
        const date = new Date(dateString);
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    }

    function formatNumber(num) {
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    function parseFansBadge(badgeStr) {
        if (!badgeStr) return null;

        const parts = badgeStr.split(' Lv.');
        if (parts.length !== 2) return null;

        return {
            name: parts[0],
            level: parseInt(parts[1])
        };
    }

    function setFansBadgeStyle(level) {
        const badgeElement = document.getElementById('fansBadgeContainer');

        badgeElement.classList.remove('badge-level-5', 'badge-level-15', 'badge-level-22',
            'badge-level-26', 'badge-level-30', 'badge-level-34', 'badge-level-38');

        if (level >= 38) {
            badgeElement.classList.add('badge-level-38');
        } else if (level >= 34) {
            badgeElement.classList.add('badge-level-34');
        } else if (level >= 30) {
            badgeElement.classList.add('badge-level-30');
        } else if (level >= 26) {
            badgeElement.classList.add('badge-level-26');
        } else if (level >= 22) {
            badgeElement.classList.add('badge-level-22');
        } else if (level >= 15) {
            badgeElement.classList.add('badge-level-15');
        } else if (level >= 5) {
            badgeElement.classList.add('badge-level-5');
        }
    }

    class VideoListManager {
        constructor() {
            this.allVideos = [];
            this.filteredVideos = [];
            this.currentPage = 1;
            this.itemsPerPage = 10;
            this.searchTerm = '';

            this.initElements();
            this.bindEvents();
        }

        initElements() {
            this.elements = {
                videoListBody: document.getElementById('videoListBody'),
                videoSearch: document.getElementById('videoSearch'),
                prevPage: document.getElementById('prevPage'),
                nextPage: document.getElementById('nextPage'),
                currentPage: document.getElementById('currentPage'),
                totalPages: document.getElementById('totalPages'),
                startItem: document.getElementById('startItem'),
                endItem: document.getElementById('endItem'),
                totalItems: document.getElementById('totalItems')
            };
        }

        bindEvents() {
            this.elements.videoSearch.addEventListener('input', (e) => {
                this.searchTerm = e.target.value.toLowerCase();
                this.currentPage = 1;
                this.filterVideos();
                this.render();
            });

            this.elements.prevPage.addEventListener('click', () => {
                if (this.currentPage > 1) {
                    this.currentPage--;
                    this.render();
                }
            });

            this.elements.nextPage.addEventListener('click', () => {
                if (this.currentPage < this.getTotalPages()) {
                    this.currentPage++;
                    this.render();
                }
            });
        }

        loadVideos(videos) {
            // 按照上传时间降序排序
            this.allVideos = videos.sort((a, b) => {
                return new Date(b.uploadDate) - new Date(a.uploadDate);
            });
            this.filteredVideos = [...this.allVideos];
            this.render();
        }

        filterVideos() {
            if (this.searchTerm === '') {
                this.filteredVideos = [...this.allVideos];
            } else {
                this.filteredVideos = this.allVideos.filter(video =>
                    video.title.toLowerCase().includes(this.searchTerm)
                );
            }
        }

        getTotalPages() {
            return Math.ceil(this.filteredVideos.length / this.itemsPerPage);
        }

        getPaginatedVideos() {
            const start = (this.currentPage - 1) * this.itemsPerPage;
            const end = start + this.itemsPerPage;
            return this.filteredVideos.slice(start, end);
        }

        render() {
            const paginatedVideos = this.getPaginatedVideos();
            const totalPages = this.getTotalPages();

            this.elements.videoListBody.innerHTML = paginatedVideos.map(video => `
                <tr>
                    <td>
                        <span class="video-title" data-bvid="${video.bvid}">${video.title}</span>
                    </td>
                    <td>${formatNumber(video.views)}</td>
                    <td>${formatNumber(video.danmaku)}</td>
                    <td>${video.duration}</td>
                    <td>${video.uploadDate}</td>
                </tr>
            `).join('');

            document.querySelectorAll('.video-title').forEach(title => {
                title.addEventListener('click', (e) => {
                    const bvid = e.target.getAttribute('data-bvid');
                    window.open(`video?bvid=${bvid}`, '_blank');
                });
            });

            this.elements.currentPage.textContent = this.currentPage;
            this.elements.totalPages.textContent = totalPages;
            this.elements.totalItems.textContent = this.filteredVideos.length;

            const startItem = (this.currentPage - 1) * this.itemsPerPage + 1;
            const endItem = Math.min(startItem + this.itemsPerPage - 1, this.filteredVideos.length);

            this.elements.startItem.textContent = startItem;
            this.elements.endItem.textContent = endItem;

            this.elements.prevPage.disabled = this.currentPage <= 1;
            this.elements.nextPage.disabled = this.currentPage >= totalPages;
        }
    }

    async function loadAllData() {
        try {
            hideError();

            const basicInfoPromise = fetchUpBasicInfo(uid);
            const videoDataPromise = fetchVideoData(uid);

            const [basicInfo, videos] = await Promise.all([
                basicInfoPromise,
                videoDataPromise
            ]);

            const videoListManager = new VideoListManager();

            if (basicInfo) {
                document.getElementById('upName').textContent = basicInfo.name;
                document.getElementById('upFans').textContent = formatNumber(basicInfo.fans);
                document.getElementById('upFollowing').textContent = formatNumber(basicInfo.following);

                const levelBadge = document.querySelector('.level-badge');
                levelBadge.textContent = `Lv.${basicInfo.level}`;

                document.getElementById('spaceLinkBtn').addEventListener('click', function() {
                    window.open(`https://space.bilibili.com/${basicInfo.uid}`, '_blank');
                });

                const badgeContainer = document.getElementById('fansBadgeContainer');
                const badgeInfo = parseFansBadge(basicInfo.fansBadge);

                if (badgeInfo) {
                    badgeContainer.style.display = 'inline-flex';
                    badgeContainer.innerHTML = `${badgeInfo.name} Lv.${badgeInfo.level}`;
                    setFansBadgeStyle(badgeInfo.level);
                }
            } else {
                document.getElementById('upName').textContent = "获取失败";
                document.getElementById('upFans').textContent = "N/A";
                document.getElementById('upFollowing').textContent = "N/A";
            }

            if (videos && videos.length > 0) {
                videoListManager.loadVideos(videos);

                const totalViews = videos.reduce((sum, video) => sum + video.views, 0);
                const totalDanmaku = videos.reduce((sum, video) => sum + video.danmaku, 0);

                document.getElementById('totalViews').textContent = formatNumber(totalViews);
                document.getElementById('totalDanmaku').textContent = formatNumber(totalDanmaku);

                const maxStat = Math.max(totalViews, totalDanmaku);
                document.getElementById('viewsProgress').style.width = `${(totalViews / maxStat) * 100}%`;
                document.getElementById('danmakuProgress').style.width = `${(totalDanmaku / maxStat) * 100}%`;
            } else {
                document.getElementById('totalViews').textContent = "N/A";
                document.getElementById('totalDanmaku').textContent = "N/A";
                document.getElementById('videoListBody').innerHTML = `
                <tr>
                    <td colspan="5" class="text-center py-4 text-gray-500">暂无视频数据</td>
                </tr>
            `;
            }

            const analysisContainer = document.getElementById('analysisResult');
            analysisContainer.innerHTML = '';

            if (!videos || videos.length === 0) {
                analysisContainer.innerHTML = '<p class="text-gray-600">没有足够的视频数据进行分析</p>';
                return;
            }

            const totalVideos = videos.length;
            const totalViews = videos.reduce((sum, video) => sum + video.views, 0);
            const totalDanmaku = videos.reduce((sum, video) => sum + video.danmaku, 0);
            const avgViews = Math.round(totalViews / totalVideos);
            const avgDanmaku = Math.round(totalDanmaku / totalVideos);

            const topVideo = [...videos].sort((a, b) => b.views - a.views)[0];
            const worstVideo = [...videos].sort((a, b) => a.views - b.views)[0];

            const uploadDates = videos.map(v => new Date(v.uploadDate).getTime());
            const oldestDate = new Date(Math.min(...uploadDates));
            const newestDate = new Date(Math.max(...uploadDates));
            const daysActive = Math.round((newestDate - oldestDate) / (1000 * 60 * 60 * 24));
            const avgDaysBetweenUploads = daysActive > 0 ? Math.round(daysActive / totalVideos) : 0;

            const durations = videos.map(v => {
                const parts = v.duration.split(':');
                if (parts.length === 3) {
                    return parseInt(parts[0]) * 3600 + parseInt(parts[1]) * 60 + parseInt(parts[2]);
                } else if (parts.length === 2) {
                    return parseInt(parts[0]) * 60 + parseInt(parts[1]);
                }
                return parseInt(parts[0]);
            });
            const avgDuration = Math.round(durations.reduce((a, b) => a + b, 0) / durations.length);
            const durationFormatted = `${Math.floor(avgDuration / 60)}分${avgDuration % 60}秒`;
            const daysSinceLastUpload = newestDate ?
                Math.round((Date.now() - newestDate.getTime()) / (1000 * 60 * 60 * 24)) : 0;

            const analysisReport = [
                `📊 基础统计: 共${totalVideos}个视频，总播放量${formatNumber(totalViews)}，平均每个视频${formatNumber(avgViews)}播放`,
                `🎯 最佳表现: "${topVideo.title}" (${formatNumber(topVideo.views)}播放)`,
                `⚠️ 最差表现: "${worstVideo.title}" (${formatNumber(worstVideo.views)}播放)`,
                `⏱️ 时长分析: 平均视频时长约${durationFormatted}`,
                `📅 更新频率: 平均${avgDaysBetweenUploads}天更新一次`,
                `⏳ 最后更新: ${daysSinceLastUpload}天前`,
                `${getResults(daysSinceLastUpload, avgDaysBetweenUploads, avgDuration)}`
            ];

            analysisReport.forEach(item => {
                const p = document.createElement('p');
                p.className = 'text-gray-600 mb-3';
                p.innerHTML = item;
                analysisContainer.appendChild(p);
            });

            function getResults(daysSinceLastUpload, avgDaysBetweenUploads, avgDuration) {
                let results = [];

                if (daysSinceLastUpload > 365) {
                    results.push('up主较长时间未更新，账号可能停运。');
                } else if (avgDaysBetweenUploads > 60) {
                    results.push('up主更新视频频率较低。');
                }

                if (avgDuration < 60*5) {
                    results.push('该up主要内容为短视频。');
                }else if (avgDuration >= 60*10){
                    results.push('该up主要内容为长视频。');
                }

                return results.length > 0 ? results.join(' ') : '';
            }


            document.getElementById('refreshVideosBtn').addEventListener('click', async function() {
                try {
                    this.disabled = true;
                    this.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>更新中...';

                    const updatedVideos = await updateVideoData(uid);
                    videoListManager.loadVideos(updatedVideos);

                    const newTotalViews = updatedVideos.reduce((sum, video) => sum + video.views, 0);
                    const newTotalDanmaku = updatedVideos.reduce((sum, video) => sum + video.danmaku, 0);

                    document.getElementById('totalViews').textContent = formatNumber(newTotalViews);
                    document.getElementById('totalDanmaku').textContent = formatNumber(newTotalDanmaku);

                    const newMaxStat = Math.max(newTotalViews, newTotalDanmaku);
                    document.getElementById('viewsProgress').style.width = `${(newTotalViews / newMaxStat) * 100}%`;
                    document.getElementById('danmakuProgress').style.width = `${(newTotalDanmaku / newMaxStat) * 100}%`;

                    alert('视频数据更新成功！');
                } catch (error) {
                    console.error('更新视频数据失败:', error);
                    showError(`更新视频数据失败: ${error.message}`);
                } finally {
                    this.disabled = false;
                    this.innerHTML = '<i class="fas fa-sync-alt mr-2"></i>更新视频数据';
                }
            });

        } catch (error) {
            console.error('加载数据失败:', error);
            showError(`加载数据失败: ${error.message}`);
        }
    }

    window.addEventListener('load', loadAllData);
</script>
</body>
</html>